#include "SignTreeModel.h"

namespace xpm {
	QVariant SignTreeModel::data(const QModelIndex& index, int role) const {
		if (!index.isValid())
			return QVariant();

		if (role == Qt::SizeHintRole) {
			if(index.column() == 0)
				return QSize(300, 35);
			else
			    return QSize(16, 35);
		} else if(role != Qt::DisplayRole)
			return QVariant();

		SDFSign *item = static_cast<SDFSign*>(index.internalPointer());

		int type = item->type();

		switch(index.column()) {
		case 0:
			return StringCovert::stdWToQString( item->de_str());
		case 1:
			return QString::number( item->type());
		case 2:
			return type2str(type);
		case 3:
			return type2value(type, item);
		default:
			return StringCovert::stdWToQString( item->de_str());
		}
	}

	QModelIndex SignTreeModel::index(int row, int column, const QModelIndex &parent) const
	{
		if (parent.isValid() && parent.column() != 0)
			return QModelIndex();

		SDFSign *parentItem;

		if (!parent.isValid())
			parentItem = _root;
		else
			parentItem = static_cast<SDFSign*>(parent.internalPointer());

		SDFSign *childItem = parentItem->at(row);
		if (childItem)
			return createIndex(row, column, childItem);
		else
			return QModelIndex();
	}

	QModelIndex SignTreeModel::parent(const QModelIndex &index) const
	{
		if (!index.isValid())
			return QModelIndex();

		SDFSign *childItem = static_cast<SDFSign*>(index.internalPointer());
		SDFSign *parentItem = childItem->parent();

		if (parentItem == _root)
			return QModelIndex();

		int row = 0;
		if(parentItem->parent() != _root) {
			for(int i = 0; i < parentItem->parent()->size(); ++i) {
				if( parentItem->parent()->at(i) == parentItem) {
					row = i;
					break;
				}
			}
		}
		return createIndex(row, 0, parentItem);
	}

	QVariant SignTreeModel::type2value(int type, SDFSign* item) const {
		switch(type) {
			case SDF_STRING:
				return StringCovert::stdWToQString(item->rei_as_string());
			case SDF_NUMBER:
				return QString::number( item->rei_as_number());
			case SDF_TRUE:
				return QString("true");
			case SDF_FALSE:
				return tr("false");
			case SDF_NULL:
				return tr("null");
			case SDF_OBJECT:
				return QString::number(item->size());
			case SDF_ARRAY:
				return QString::number(item->size());
			default:
				return tr("null");
		}
	}

	QVariant SignTreeModel::type2str(int type) const {
		switch(type) {
			case SDF_STRING:
				return tr("string");
			case SDF_NUMBER:
				return tr("number");
			case SDF_TRUE:
			case SDF_FALSE:
				return tr("bool");
			case SDF_NULL:
				return tr("null");
			case SDF_OBJECT:
				return tr("object");
			case SDF_ARRAY:
				return tr("array");
			default:
				return tr("null");
		}
	}
}